package com.danskin.wechat.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;  
import javax.net.ssl.TrustManager;  
import javax.net.ssl.X509TrustManager;  
import javax.script.Invocable;  
import javax.script.ScriptEngine;  
import javax.script.ScriptEngineManager;

import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.Scheme;  
import org.apache.http.conn.scheme.SchemeRegistry;  
import org.apache.http.conn.ssl.SSLSocketFactory;  
import org.apache.http.cookie.Cookie;  
import org.apache.http.impl.client.DefaultHttpClient;  
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;  
import org.apache.http.message.BasicNameValuePair;  
import org.apache.http.util.EntityUtils;  
 
import org.jeewx.api.core.common.MyX509TrustManager;

public class ImageDownloadUtil {

	public static File downloadImage(String url, String parentPath) throws IOException {
		String fileName = saveImg(url, parentPath);
		File image = new File(parentPath + File.separator + fileName);
		return image;
	}

	public static String saveImg(String urlStr, String parent_path) throws IOException {
		InputStream is = null;
		FileOutputStream fos = null;

		String file_name = System.currentTimeMillis() + ".jpg";

		try {
			URL url = new URL(urlStr);
			//URLConnection connection = url.openConnection();
			HttpURLConnection conn = getConnection("GET", url); 
			// System.setProperty("https.protocols", "TLSv1.1,TLSv1.2");

			is = conn.getInputStream();
			byte[] temp = new byte[1024];
			int len = 0;
			File dir = new File(parent_path);
			if (!dir.exists())
				dir.mkdirs();
			fos = new FileOutputStream(dir + File.separator + file_name);
			while ((len = is.read(temp)) != -1)
				fos.write(temp, 0, len);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				is.close();

			}
			if (fos != null) {
				fos.close();

			}
		}
		return file_name;
	}

	private static HttpURLConnection getConnection(String method, URL url) throws IOException {
		HttpURLConnection conn = null;
		if ("https".equals(url.getProtocol())) {
			SSLContext context = null;
			try {
				context = SSLContext.getInstance("SSL", "SunJSSE");
				context.init(new KeyManager[0], new TrustManager[] { new MyX509TrustManager() },

						new java.security.SecureRandom());
			} catch (Exception e) {
				throw new IOException(e);
			}
			HttpsURLConnection connHttps = (HttpsURLConnection) url.openConnection();
			connHttps.setSSLSocketFactory(context.getSocketFactory());
//			connHttps.setHostnameVerifier(new HostnameVerifier() {
//
//				@Override
//				public boolean verify(String arg0, SSLSession arg1) {
//					return true;
//				}
//			}); 
			conn = connHttps; 
		} else {
			conn = (HttpURLConnection) url.openConnection();
		}
		conn.setRequestMethod(method);
		conn.setUseCaches(false);
		conn.setDoInput(true);
		conn.setDoOutput(true);
		return conn;
	}

	public static String urlEncode(String source, String encode) {
		String result = source;
		try {
			result = URLEncoder.encode(source, encode);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}
	public static ThreadSafeClientConnManager getClientManager() throws Exception {  
        SSLContext ctx = SSLContext.getInstance("TLS");  
        X509TrustManager tm = new MyX509TrustManager();  
          
        ctx.init(null, new TrustManager[] { tm }, null);  
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
        SchemeRegistry registry = new SchemeRegistry();  
        registry.register(new Scheme("https", 443, ssf));  
        ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(registry);  
          
        return mgr;  
    }   
	public static void downLoad(String remoteFileName, String localFileName) throws Exception {
		
//		ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();    
//        Protocol.registerProtocol("https", new Protocol("https", fcty, 443));   
//        DefaultHttpClient httpClient = new DefaultHttpClient(getClientManager());
 System.setProperty("javax.net.debug","ssl");
		HttpClient client = new DefaultHttpClient();  
         client = WebClientDevWrapper.wrapClient(client);  
        OutputStream out = null;
        InputStream in = null;
        
        try {
            HttpGet httpGet = new HttpGet(remoteFileName);

//            httpGet.addHeader("userName", userName);
//            httpGet.addHeader("passwd", passwd);
//            httpGet.addHeader("fileName", remoteFileName);

            HttpResponse httpResponse = client.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
            in = entity.getContent();

            long length = entity.getContentLength();
            if (length <= 0) {
                System.out.println("下载文件不存在！");
                return;
            }
 
            File file = new File(localFileName);
            if(!file.exists()){
                file.createNewFile();
            }
            
            out = new FileOutputStream(file);  
            byte[] buffer = new byte[4096];
            int readLength = 0;
            while ((readLength=in.read(buffer)) > 0) {
                byte[] bytes = new byte[readLength];
                System.arraycopy(buffer, 0, bytes, 0, readLength);
                out.write(bytes);
            }
            
            out.flush();
            
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                if(in != null){
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            
            try {
                if(out != null){
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
	public static void main(String[] args) throws Exception {

		downloadImage( "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQGU8DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyZmV3RXNEakJmZmwxLTRMVk5wY1oAAgTxGd5ZAwST1RsA",
				"test");
	}
}
